package data_api

import (
	"gin_study_blog/common"
	"gin_study_blog/common/http"
	"gin_study_blog/models"
	"github.com/gin-gonic/gin"
	"time"
)

type DateCount struct {
	Date  string `json:"date"`
	Count int    `json:"count"`
}

type dateCountResponse struct {
	DateList  []string `json:"date_list"`
	LoginData []int    `json:"login_data"`
	SignData  []int    `json:"sign_data"`
}

func (DataApi) SevenLoginView(c *gin.Context) {
	var loginDateCount, signDateCount []DateCount
	common.DB.Model(models.LoginDataModel{}).
		Where("date_sub(curdate(), interval 7 day) <= created_at").
		Select("date_format(created_at, '%Y-%m-%d') as date", "count(id) as count").
		Group("date").
		Scan(&loginDateCount)
	common.DB.Model(models.UserModel{}).
		Where("date_sub(curdate(), interval 7 day) <= created_at").
		Select("date_format(created_at, '%Y-%m-%d') as date", "count(id) as count").
		Group("date").
		Scan(&signDateCount)

	now := time.Now()
	loginDateCountMap := map[string]int{}
	signDateCountMap := map[string]int{}
	var loginCount, signCount []int
	for _, v := range loginDateCount {
		loginDateCountMap[v.Date] = v.Count
	}
	for _, v := range signDateCount {
		signDateCountMap[v.Date] = v.Count
	}
	var dateList []string
	for i := -6; i <= 0; i++ {
		day := now.AddDate(0, 0, i).Format("2006-01-02")
		dateList = append(dateList, day)
		loginCount = append(loginCount, loginDateCountMap[day])
		signCount = append(signCount, signDateCountMap[day])
	}

	http.IsOkWithData(dateCountResponse{
		DateList:  dateList,
		LoginData: loginCount,
		SignData:  signCount,
	}, c)
}
